package com.js.foodordersystem.config;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.js.foodordersystem.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的拦截器类 - 实现 HandlerInterceptor 接口
 */
@Component
@Slf4j
public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在这里编写拦截逻辑，类似过滤器
        if (shouldBypass(request)) {
            return true;
        }
        if (isValidToken(request)) {
            return true;
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Token失效，请重新登录");
            return false;
        }
    }

    private boolean isValidToken(HttpServletRequest request) {
        DecodedJWT decodedJWT = JwtUtil.verifyToken(request.getHeader("token"));
        return decodedJWT != null;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("请求拦截器 - 在请求处理之后调用，但在视图被渲染之前");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("请求拦截器 - 在请求处理完成后调用");
    }

    // 自定义放行逻辑，例如针对某些接口放行
    private boolean shouldBypass(HttpServletRequest request) {
        //放行登录接口和注册接口
        String uri = request.getRequestURI();
        return uri.contains("/user/login") ||
                uri.contains("/user/register") ||
                uri.contains("/upload/img") ||
                uri.contains("/alipay/returnUrl") ||
                uri.contains("/alipay/notifyUrl") ||
                uri.contains("/images/") ||
                uri.contains("/dishCategory/findAllCategory") ||
                uri.contains("/dish/getRandom") ||
                uri.contains("/dish/getPopular") ||
                uri.contains("/dish/findAll") ||
                uri.contains("/restaurant/findAll") ||
                uri.contains("/dish/getByCreatedAt") ||
                uri.contains("/dish/getByRestaurantId") ||
                uri.contains("/error");
    }
}
